/**
 * This is a work in progress. Right now it is incredibly simple
 * because its objectives are hazily defined. Once the certificate
 * structure is finished, this can be fleshed out.
 * @author Henry Mozer
 */
function Storage() {
	// PRIVATE
	// For convenience, what we want to manipulate
	var storage = chrome.storage.sync;

	// Makes sure the certificates object exists
	storage.get('certificates', function(items) {
		if (!items.certificates) {
			var certs = new Object();
			certs.unique = 0;
			certs.total  = 0;
			certs.failed = 0;
			storage.set({'certificates': certs});
		}
	});

	// PUBLIC
	this.getCert = function(url) {
		// TODO: hash
		var obj;
		storage.get('certificates', function(items) {
			obj = items.certificates[url];
			if (obj != null) {
				items.certificates.total = items.certificates.total + 1;
			}
		});
		return obj;
	};

	this.setCert = function(url, cert) {
		// TODO: hash
		storage.get('certificates', function(items){
			var certs = items.certificates;
			if (certs[url] == null) {
				certs.unique = certs.unique + 1;
			} else if (!cert) {
				certs.failed = certs.failed + 1;
			}
			certs.total = certs.total + 1;
			certs[url] = cert;
		});
		return;
	};

	this.clearCerts = function() {
		storage.get('certificates', function(items){
			delete items.certificates;
			var certs = new Object();
			certs.unique = 0;
			certs.total  = 0;
			certs.failed = 0;
			items.certificates = certs;
		});
	};

	this.getUniques = function() {
		var n = 0;
		storage.get('certificates', function(items) {
			n = items.certificates.unique;
		});
		return n;
	};

	this.getTotal = function() {
		var n = 0;
		storage.get('certificates', function(items) {
			n = items.certificates.total;
		});
		return n;
	};

	this.getSuccessRate = function() {
		var n = 0;
		storage.get('certificates', function(items) {
			n = items.certificates.failed / items.certificates.total;
		});
		n = Math.round(100 - 100*n);
		return n;
	};

	this.clearStats = function() {
		storage.get('certificates', function(items) {
			items.certificates.failed = 0;
			items.certificates.total = 0;
			items.certificates.unique = 0;
		});
	};

	this.toString = function() {
		//for cert in storage {
		//	storage[cert];
		//}
		return "Not implemented yet,\nwaiting on certificate structure.";
	};
}

